/* ============================================================================= */
/*      TABLE 9 - FIRM GROWTH AND EMPLOYMENT (ACCEPTED VS REJECTED - MATCHED)     */
/* ============================================================================= */

clear all

//----------------------------------------------------------------------------//
//                 STEP 1: PREPARE MATCHED SAMPLE WEIGHTS                      //
//----------------------------------------------------------------------------//

use "$output\rejected_psm.dta", clear
    keep siren weight
    sort siren
    quietly by siren: gen dup = cond(_N == 1, 0, _n)
    drop if dup > 1
    save "$output\matched_weights_rejected.dta", replace	

//----------------------------------------------------------------------------//
//                 STEP 2: LOAD & CLEAN UNMATCHED SAMPLE                       //
//----------------------------------------------------------------------------//

use "$output\scr_fiben_reject.dta", clear

    /* Industry Merging */
    replace industry = "public" if inlist(industry, "P", "Q", "R", "S")
    replace industry = "DE" if inlist(industry, "D", "E")
    replace industry = "FL" if inlist(industry, "F", "L")

    /* Drop irrelevant industries */
    drop if inlist(industry, "A", "K", "O", "B", "DE", "0000Z")

    /* Keep observations before 2020 */
    keep if mdate < mofd(date("20200101","YMD"))

    /* Generate key financial variables */
    gen lasset = log(assets)
    gen lassetfilled = log(assets_filled)
    replace investment = r12filled
    gen linvestment = log(investment)
    gen rsales = r5filled
    gen lsales = log(sales)
    gen lemployment = log(employees)
    gen lcollat = log(immo_corpo)
    gen collat = r_collateral_filled
    gen loan = drawn + available

    egen nesc = group(activity)

    keep lasset linvestment lsales lcollat investment rsales lemployment collat r14 siren accepted post mdate deltamonths year nesc outsideloandate date loan outsideloan rate maturity lassetfilled dettefiscta dettefouta assets salaires_orbis r1 r_collateral_filled r5filled employees r3 inventory cash dettefou creclie dettefisc otherwc

//----------------------------------------------------------------------------//
//                 STEP 3: YEARLY AGGREGATION & POST-LOAN FLAG                 //
//----------------------------------------------------------------------------//

    * Convert month data to year data
    gen year_loan = substr(outsideloandate, 1, 4)
    destring year_loan, replace
    gen delta_year = year - year_loan

    * Keep only December observations
    gen monthkeep = substr(date, 6, 2)
    keep if monthkeep == "12"

    * Define post-loan period
    gen post = year >= year_loan

    preserve
        collapse (sum) loan, by(siren delta_year)
        save "$output\siren_loan_volume_rejected.dta", replace
    restore

    collapse (mean) lasset linvestment lsales lcollat investment rsales lemployment collat r14 lassetfilled dettefiscta dettefouta ldettefiscta ldettefouta /*
    */ assets salaires_orbis r1 r_collat r5filled employees r3 inventory cash dettefou creclie dettefisc otherwc, ///
    by(siren accepted year delta_year nesc post)

    xtset siren year
    gen assets_pre = L.assets

    * Normalize key financials by pre-treatment assets
    foreach var of varlist r3 r1 collat rsales dettefiscta dettefouta {
        gen `var'_pre = `var' * assets / assets_pre
    }

    foreach var of varlist inventory cash creclie dettefou dettefisc otherwc {
        gen `var'_pre = `var' / assets_pre
    }

    merge m:1 siren delta_year using "$output\siren_loan_volume_rejected.dta"
    keep if _merge == 3
    drop _merge

//----------------------------------------------------------------------------//
//                 STEP 4: MERGE MATCHED SAMPLE & APPLY WEIGHTS                //
//----------------------------------------------------------------------------//

    merge m:1 siren using "$output\matched_weights_rejected.dta"
    keep if _merge == 3
    drop _merge

    keep if delta_year >= -4 & delta_year <= 4
    replace delta_year = delta_year + 6

    * Compute Working Capital excluding `dettefou`
    gen wc_no_dettefou = inventory_pre + cash_pre + creclie_pre + otherwc_pre - dettefisc_pre

//----------------------------------------------------------------------------//
//                 STEP 5: WINSORIZE EXTREME VALUES                            //
//----------------------------------------------------------------------------//

    foreach var of varlist lasset lsales lemployment lcollat ldettefisct ldettefou r3 r1 *_pre wc* {
        su `var', d
        gen `var'_wsr = `var' if `var' > `r(p1)' & `var' < `r(p99)' & `var' !=.
        replace `var'_wsr = `r(p1)' if `var' < `r(p1)' & `var' !=.
        replace `var'_wsr = `r(p99)' if `var' > `r(p99)' & `var' !=.
    }

//----------------------------------------------------------------------------//
//                 STEP 6: REGRESSIONS                                         //
//----------------------------------------------------------------------------//

    capture estimates drop *

    qui eststo reg1: reghdfe lasset i1.accepted##i1.post [pweight=weight], a(i.siren i.nesc#i.year) cluster(siren) 
	estadd local firm "Y", replace 
	estadd local indyear "Y", replace  
    qui eststo reg2: reghdfe lcollat i1.accepted##i1.post [pweight=weight], a(i.siren i.nesc#i.year) cluster(siren) 
	estadd local firm "Y", replace 
	estadd local indyear "Y", replace  
    qui eststo reg3: reghdfe lemployment i1.accepted##i1.post [pweight=weight], a(i.siren i.nesc#i.year) cluster(siren) 
	estadd local firm "Y", replace 
	estadd local indyear "Y", replace  
    qui eststo reg4: reghdfe r1_pre_wsr i1.accepted##i1.post [pweight=weight], a(i.siren i.nesc#i.year) cluster(siren) 
	estadd local firm "Y", replace 
	estadd local indyear "Y", replace  
    qui eststo reg5: reghdfe dettefou_pre_wsr i1.accepted##i1.post [pweight=weight], a(i.siren i.nesc#i.year) cluster(siren) 
	estadd local firm "Y", replace 
	estadd local indyear "Y", replace  
    qui eststo reg6: reghdfe wc_no_dettefou_wsr i1.accepted##i1.post [pweight=weight], a(i.siren i.nesc#i.year) cluster(siren) 
	estadd local firm "Y", replace 
	estadd local indyear "Y", replace  

//----------------------------------------------------------------------------//
//                 STEP 7: EXPORT TABLE 8b TO LaTeX                             //
//----------------------------------------------------------------------------//

    esttab * using "$tables\real_firm_outcome_rejected.tex", replace ///
        noomitted nobase fragment gap booktabs label nonote noobs nolines /// 
        b(%9.3f) drop(_cons) se(%9.3f) star(* 0.10 ** 0.05 *** 0.01) ///
        mtitles("Assets" "Tangible assets" "Employment" "Working capital" "WC: Payables" "WC: Others") ///
        order(1.accepted#1.post 1.post) ///
        varlabel(1.post "Post" 1.accepted#1.post `"Accepted $\times$ Post"') ///
        stats(firm indyear N r2, label(`"Firm FE"' `"Industry-Year FE"' `"\midrule N"' `"R-sq"') layout("\multicolumn{1}c{@}")) 
